package cn.yr.search.service.impl;

import cn.yr.common.core.domain.vo.PageVo;
import cn.yr.search.bean.ArticleDocBean;
import cn.yr.search.repository.ArticleElasticRepository;
import cn.yr.search.service.ArticleElasticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service("articleElasticService")
public class ArticleElasticServiceImpl implements ArticleElasticService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Autowired
    private ArticleElasticRepository articleElasticRepository;

    @Override
    public Boolean createIndex() {
        return elasticsearchTemplate.indexOps(ArticleDocBean.class).create();
    }

    @Override
    public Boolean deleteIndex() {
        return elasticsearchTemplate.indexOps(ArticleDocBean.class).delete();
    }

    @Override
    public void save(ArticleDocBean articleDocBean) {
        articleElasticRepository.save(articleDocBean);
    }

    @Override
    public void saveAll(List<ArticleDocBean> list) {
        articleElasticRepository.saveAll(list);
    }

    @Override
    public void delete(Long id) {
        articleElasticRepository.deleteById(id);
    }

    @Override
    public void update(ArticleDocBean articleDocBean){
        articleElasticRepository.save(articleDocBean);
    }

    @Override
    public Iterator<ArticleDocBean> findAll() {
        return articleElasticRepository.findAll().iterator();
    }

    @Override
    public PageVo<ArticleDocBean> findByTitle(PageVo<ArticleDocBean> pageVo) {
        Pageable pageable = PageRequest.of( (int) pageVo.getCurrent(),(int) pageVo.getSize());
        Page<ArticleDocBean> page = articleElasticRepository.findByTitle(pageVo.getAs("kw"), pageable);
        pageVo.setRecords(page.getContent());
        pageVo.setTotal(page.getTotalElements());
        return  pageVo;
    }

    @Override
    public PageVo<ArticleDocBean> find(PageVo<ArticleDocBean> pageVo) {
        Pageable pageable = PageRequest.of( (int) pageVo.getCurrent(),(int) pageVo.getSize());
        Page<ArticleDocBean> page = articleElasticRepository.find(pageVo.getAs("kw"), pageable);
        pageVo.setRecords(page.getContent());
        pageVo.setTotal(page.getTotalElements());
        return pageVo;
    }

    @Override
    public Page<ArticleDocBean> findByFirstCode(String firstCode) {
        return null;
    }

    @Override
    public Page<ArticleDocBean> findBySecordCode(String secordCode) {
        return null;
    }

    @Override
    public Page<ArticleDocBean> query(String key) {
        return null;
    }
}
